<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
    >
      <template #tableHeader="scope">
        <el-form>
          <el-row :gutter="20">
            <!-- 第一个表单项 -->
            <el-col :span="12">
              <el-form-item label="模型选择：">
                <el-select v-model="modelId" placeholder="请选择模型">
                  <el-option
                    v-for="option in modelOptions"
                    :key="option.modelId"
                    :label="option.modelName"
                    :value="option.modelId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 第二个表单项 -->
            <el-col :span="12">
              <el-form-item label="模型实例选择：">
                <el-select v-model="modelIntanceId" placeholder="请选择模型实例">
                  <el-option
                    v-for="option in modelIntanceOptions"
                    :key="option.modelInstanceId"
                    :label="option.modelInstanceName"
                    :value="option.modelInstanceId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <div>
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                :action="upload.url"
                :headers="upload.headers"
                :on-success='handleSuccess'
                :before-upload="beforeAvatarUpload"
              >
                <div style="display: flex; align-items: center;">
                  <el-button type="primary">上传文档</el-button>
                </div>
              </el-upload>
            </div>
            <div>
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                action=""
                :http-request="submitUpload"
                :headers="upload.headers"
                :limit="1"
              >
                <div style="display: flex; align-items: center;">
                  <el-button type="success"  style="float: right; margin-left: 10px;">诊断</el-button>
                </div>
              </el-upload>
            </div>

          </el-row>
        </el-form>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">训练</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>

    <basicForm ref="drawerRef" />
    <ModelDrawer ref="drawerRef" />
<!--    <ImportExcel ref="dialogRef" />-->

    <el-dialog v-model="show" width="86%"  >
<!--      <template >-->
        <!-- 选择区段 -->
        <div style="float: left; padding: 3px 0" >
          <el-radio style="margin-right: auto" v-model="sectionIndex" :label="0" border>前区段</el-radio>
          <el-radio style="margin-right: auto" v-model="sectionIndex" :label="1" border>本区段</el-radio>
          <el-radio style="margin-right: auto" v-model="sectionIndex" :label="2" border>后区段</el-radio>
        </div>
        <el-tooltip effect="dark" placement="left" style="float: right;">
          <div slot="content">
            <p>1、实线为左边坐标系，虚线为右边坐标系</p>
          </div>
          <i class="el-icon-warning" style="font-size: 20px;"></i>
        </el-tooltip>
<!--      </template>-->
      <div v-if="show" class="chart-container">
        <InitEcharts :data="datas[sectionIndex]" :chartName="chartName" :height="'100%'" :width="'100%'"></InitEcharts>
      </div>



    </el-dialog>

  </div>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { Model } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import {ElMessage, ElMessageBox, UploadRequestOptions} from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ModelDrawer from "@/views/proTable/components/ModelDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh } from "@element-plus/icons-vue";
import {
  deleteDiagnoseResult,
  queryDiagnoseResult,
  addModel,
  updateModel,
  deleteModel,
  getDModelList,
  getModelIntanceList, uploadFileDiagnoseResult,
} from "@/api/modules/new2";
import http from "@/api";
import { ElUpload } from 'element-plus';
import {BatchAddUser, exportUserInfo} from "@/api/modules/user";
import { watch } from 'vue';
import {useUserStore} from "@/stores/modules/user";
import InitEcharts from "@/views/diagnosisCenter/components/initEcharts.vue";

// 下拉框相关
// 定义下拉框的选项变量
const modelId = ref(null);
const modelOptions = ref([]);
const modelIntanceId = ref(null);
const modelIntanceOptions = ref([]);
// 定义下拉框选择的模型 ID
const selectedModel = ref(null);

const fileList2 = ref([]); // 在 setup 函数中定义 fileList
const  featuresWindowShow = ref(false) ; //特征查看窗口显隐

const uploadRef = ref<ElUpload | null>(null);

onMounted(() => {
  // 初始化fileList1
  fileList2.value = []; // 或者将初始文件列表赋值给它
  uploadRef.value = ref('uploadRef')?.value;
  // 在组件挂载时获取模型数据
   // 在组件挂载时获取模型列表
  fetchModelOptions();
  fetchModelIntanceOptions();

});

const router = useRouter();

const proTable = ref<ProTableInstance>();

const initParam = reactive({ type: 1 });

const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};
const userStore = useUserStore();

/*** 用户导入参数 */
const upload = reactive({

  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（批量邀约）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { 'x-access-token': userStore.token },
  // 上传的地址
  url: import.meta.env.VITE_API_URL + "/python-api/display_data"
});


const getTableList = (params: any) => {

  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return queryDiagnoseResult(newParams);
};

const { BUTTONS } = useAuthButtons();

const columns = reactive<ColumnProps<Model.ResModelList>[]>([
  // { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "Sort", width: 80 },
  // { type: "expand", label: "Expand", width: 85 },
  {
    prop: "diagnoseResultId",
    label: "诊断结果Id",
  },
  {
    prop: "fileName",
    label: "文件名",
  },
  {
    prop: "filePath",
    label: "文件路径",
  },
  {
    prop: "diagnose_model",
    label: "诊断模型",
  },
  {
    prop: "modelInstanceName",
    label: "模型实例名称",
  },
  {
    prop: "diagnoseTime",
    label: "诊断时间",
  },
  {
    prop: "dataLength",
    label: "数据长度",
  },
  {
    prop: "timeSpan",
    label: "时间跨度",
  },

  {
    prop: "numSegments",
    label: "分段数目",
  },
  {
    prop: "diagnoseResult",
    label: "诊断结果",
  },
  {
    prop: "resultDescription",
    label: "结果描述",
  },
  {
    prop:"diagnoseElapsedTime",
    label:"诊断所需时间",
  },
  { prop: "operation", label: "操作", fixed: "right", width: 80 }
]);

const drawerRef = ref<InstanceType<typeof ModelDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Model.ResModelList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addModel : title === "编辑" ? updateModel : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

const deleteAccount = async (params) => {
  await useHandleData(deleteDiagnoseResult, { diagnoseResultId: [params.diagnoseResultId] }, `删除诊断结果【${params.diagnoseResultId}】`);
  proTable.value?.getTableList();
};
const uploadFile = ref(null); // 在 setup 函数中定义 fileList
const beforeAvatarUpload=  (file) =>{

  uploadFile.value=file
}
const batchDelete = async (id: string[]) => {
  let modelId = id.map(item => item.modelId);
  await useHandleData(deleteModel, { modelId }, "删除所选模型信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {

  ElMessage.success("修改列表排序成功");
};

const handleFileChange = (file, fileList) => {
  // 更新fileList2
  fileList2.value = fileList;
};

const sectionIndex=ref(1);
const modelIndex=ref(1);
const datas=ref();

// 文件上传
const uploadExcel =  (param: UploadRequestOptions) => {
  console.log(param)
  let excelFormData = new FormData();
  excelFormData.append("file", param.file);
  console.log(excelFormData)
}


const chartName=ref("曲线图")
const featuresWindowRowData=ref()
const rowFeatureShow=ref(true)
const mutiSection=ref(true)
const show=ref(false)


const handleSuccess = (res:any)=>{
  if (res.code === 0) {
    ElMessage.success(res.message)
    let data = [[], [], []]
    data[0]= res.data.前区段
    data[1]= res.data.本区段
    data[2]= res.data.后区段
    datas.value=data
    show.value=true


  }else{
    ElMessage.error(res.message)

  }

}





const submitUpload = async (item) => {
  console.log(item)
  if (modelId.value==null||modelIntanceId.value==null){
    ElMessage({
      message: "请选择模型实例和模型",
      type:"warning"
    });
    return;
  }

  const _modelId= modelId.value
  const _modelInstanceId=modelIntanceId.value
  await nextTick();
  if (!uploadRef.value) {
    console.error('上传组件未定义');
    return;
  }
  ElMessage({
    showClose: true,
    message: '正在诊断',
  })
  const response=await uploadFileDiagnoseResult({modelId: _modelId, modelInstanceId: _modelInstanceId, file: item.file})
    .then(response => {
      let message = "未发现故障";
      if (response.data.length!=0){
        let diagnosisData = response.data;
         message = diagnosisData.map(item =>`
          <div>
            <h3>${item.faultName}</h3>
            <p>故障设备：${item.falutFacility}</p>
            <p>故障区域：${item.faultArea}</p>
            <p>故障危险等级：${item.faultDangerLevel}</p>
            <p>故障现象：${item.faultPhenomenon}</p>
            <p>故障概率：${item.faultProbability}</p>
            <p>诊断所需时间：${item.diagnoseElapsedTime}</p>
            <p>修复建议：${item.repairAdvice}</p>
            <p>开始时间：${item.startTime}</p>
            <p>结束时间：${item.endTime}</p>
          </div>`

).join('');
      }

      ElMessageBox({
        message: message,
        dangerouslyUseHTMLString: true,
      });
      proTable.value?.getTableList();
    })
    .catch(error => {
      console.error('文件上传失败：', error);
      ElMessage.error('文件上传失败，请重试！');
    });

};
// 导入诊断数据
const ImportDiagnosisFile = () => {
  const params = {
    tempApi: exportUserInfo,
    importApi: BatchAddUser,
    getTableList: proTable.value?.getTableList
  };
  dialogRef.value?.acceptParams(params);
};

const dialogRef = ref<InstanceType<typeof ImportDiagnosisFile> | null>(null);

// 下拉框相关代码
// 获取模型数据并更新下拉框选项
// 模型Id下拉框
const fetchModelOptions = async () => {
      try {
        const response = await getDModelList({type: 1, pageNum: 1, pageSize: 50});
        if (response.data) {
          // 将获取到的模型数据赋值给 modelOptions
          modelOptions.value = response.data.list;
          // console.log("zhes", modelOptions.value);
        }
      } catch (error) {
        console.error('Error fetching model options:', error);
      }
};
watch(modelId, (newModelId) => {
    fetchModelIntanceOptions(newModelId);

  });
// 模型实例下拉框
const fetchModelIntanceOptions = async (selectModelId) => {
    try {
      if (selectModelId) {
        const response = await getModelIntanceList({ modelId: selectModelId, pageNum: 1, pageSize: 8 });
        if (response.data) {
          // 将获取到的模型实例数据赋值给 modelIntanceOptions
          modelIntanceOptions.value = response.data.list;
        }
      }
    } catch (error) {
      console.error('Error fetching modelIntance options:', error);
    }
  };

</script>
<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  height: 65vh;
}
.el-dialog{
  position: absolute;
}
</style>
